package com.milotnt.controller;

import com.milotnt.pojo.ClassOrder;
import com.milotnt.pojo.ClassTable;
import com.milotnt.pojo.Member;
import com.milotnt.pojo.Equipment;
import com.milotnt.service.ClassOrderService;
import com.milotnt.service.ClassTableService;
import com.milotnt.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.milotnt.service.EquipmentService;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * @author ZhangMing [1157038410@qq.com]
 * @date 2021/8/21
 */

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private ClassTableService classTableService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private ClassOrderService classOrderService;

    @Autowired
    private EquipmentService equipmentService;


    //跳转个人信息页面
    @RequestMapping("/toUserInfo")
    public String toUserInformation(Model model, HttpSession session) {
        Member member = (Member) session.getAttribute("user");
        model.addAttribute("member", member);
        return "userInformation";
    }

    //跳转修改个人信息页面
    @RequestMapping("/toUpdateInfo")
    public String toUpdateUserInformation(HttpSession session, Model model) {
        Member member = (Member) session.getAttribute("user");
        model.addAttribute("member", member);
        return "updateUserInformation";
    }

    //修改个人信息
    @RequestMapping("/updateInfo")
    public String updateUserInformation(HttpSession session, Member member) {
        Member member1 = (Member) session.getAttribute("user");

        member.setMemberAccount(member1.getMemberAccount());
        member.setCardClass(member1.getCardClass());
        member.setCardTime(member1.getCardTime());
        member.setCardNextClass(member1.getCardNextClass());

        memberService.updateMemberByMemberAccount(member);
        return "userInformation";
    }

    //跳转我的课程页面
    @RequestMapping("/toUserClass")
    public String toUserClass(Model model, HttpSession session) {
        Member member = (Member) session.getAttribute("user");
        model.addAttribute("member", member);
        Integer memberAccount = member.getMemberAccount();
        List<ClassOrder> classOrderList = classOrderService.selectClassOrderByMemberAccount(memberAccount);
        model.addAttribute("classOrderList", classOrderList);
        return "userClass";
    }

    // 退课
    @RequestMapping("delUserClass")
    public String deleteUserClass(@RequestParam("classOrderId") Integer classOrderId,
                                  HttpSession session,
                                  RedirectAttributes redirectAttributes) {
        try {
            // 获取当前用户
            Member member = (Member) session.getAttribute("user");
            if (member == null) {
                redirectAttributes.addFlashAttribute("errorMessage", "请先登录");
                return "redirect:toUserClass";
            }

            // 验证 classOrderId 是否有效
            if (classOrderId == null) {
                redirectAttributes.addFlashAttribute("errorMessage", "无效的课程订单 ID");
                return "redirect:toUserClass";
            }

            // 获取退课的课程信息
            ClassTable classTable = classOrderService.getClassTableByClassOrderId(classOrderId);
            if (classTable != null) {
                // 计算课程所需课时
                BigDecimal classTimeInHours = calculateClassHours(classTable);

                // 更新会员剩余课时
                BigDecimal cardNextClass = BigDecimal.valueOf(member.getCardNextClass());
                member.setCardNextClass(cardNextClass.add(classTimeInHours).doubleValue());
                session.setAttribute("user", member);

                // 更新数据库中的剩余课时
                memberService.updateMemberCardNextClass(member.getMemberAccount(), member.getCardNextClass());
            }

            // 删除课程订单
            classOrderService.deleteByClassOrderId(classOrderId);

            // 更新用户界面提示
            redirectAttributes.addFlashAttribute("successMessage", "退课成功");

        } catch (Exception e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("errorMessage", "退课失败，请稍后重试");
        }

        return "redirect:toUserClass";
    }

    //跳转报名选课页面
    @RequestMapping("/toApplyClass")
    public String toUserApplyClass(Model model, HttpSession session) {
        Member member = (Member) session.getAttribute("user");
        List<ClassTable> classList = classTableService.findAll();
        model.addAttribute("member", member);
        model.addAttribute("classList", classTableService.findAll());
        return "userApplyClass";
    }

    // 报名选课
    @RequestMapping("/applyClass")
    public String userApplyClass(Integer classId, Model model, HttpSession session, RedirectAttributes redirectAttributes) {
        // 检查用户是否登录
        Member member = (Member) session.getAttribute("user");
        if (member == null) {
            model.addAttribute("errorMessage", "请先登录");
            // 获取并传递已选课程数据
            addClassOrdersToModel(member, model);
            return "userClass";
        }

        // 在方法开始处声明memberAccount，确保整个方法都能访问
        Integer memberAccount = member.getMemberAccount();

        // 获取课程信息
        ClassTable classTable = classTableService.selectByClassId(classId);
        if (classTable == null) {
            model.addAttribute("errorMessage", "课程不存在");
            // 获取并传递已选课程数据
            addClassOrdersToModel(member, model);
            return "userClass";
        }

        // 计算课程所需课时
        BigDecimal classTimeInHours = calculateClassHours(classTable);

        // 检查剩余课时是否足够
        if (checkInsufficientHours(member, classTimeInHours, model)) {
            // 获取并传递已选课程数据
            addClassOrdersToModel(member, model);
            return "userClass";
        }

        // 检查是否重复报名
        if (checkDuplicateRegistration(classId, member, model)) {
            // 获取并传递已选课程数据
            addClassOrdersToModel(member, model);
            return "userClass";
        }

        // 检查时间冲突
        if (checkTimeConflict(classTable, member, model)) {
            // 获取并传递已选课程数据
            addClassOrdersToModel(member, model);
            return "userClass";
        }

        // 执行选课逻辑
        try {
            performEnrollment(classId, classTable, member, session);
            return "redirect:toUserClass"; // 选课成功，重定向
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("errorMessage", "报名失败，请稍后重试");
            // 获取并传递已选课程数据
            addClassOrdersToModel(member, model);
            return "userClass";
        }
    }

    // 辅助方法 - 计算课程所需课时
    private BigDecimal calculateClassHours(ClassTable classTable) {
        String classTimeStr = classTable.getClassTime();
        Integer classTimeInMinutes = Integer.valueOf(classTimeStr);
        return BigDecimal.valueOf(classTimeInMinutes)
                .divide(BigDecimal.valueOf(60), 2, RoundingMode.HALF_UP);
    }

    // 辅助方法 - 检查课时是否足够
    private boolean checkInsufficientHours(Member member, BigDecimal classTimeInHours, Model model) {
        BigDecimal cardNextClass = BigDecimal.valueOf(member.getCardNextClass());
        if (cardNextClass.compareTo(classTimeInHours) < 0) {
            model.addAttribute("errorMessage", "剩余课时不足，当前剩余 " +
                    cardNextClass.setScale(1, RoundingMode.HALF_UP) +
                    " 小时，课程需要 " + classTimeInHours + " 小时");
            return true;
        }
        return false;
    }

    // 辅助方法 - 检查是否重复报名
    private boolean checkDuplicateRegistration(Integer classId, Member member, Model model) {
        Integer memberAccount = member.getMemberAccount();
        if (classOrderService.selectMemberByClassIdAndMemberAccount(classId, memberAccount) != null) {
            model.addAttribute("errorMessage", "⚠️ 您已经报名过该课程！");
            return true;
        }
        return false;
    }

    // 辅助方法 - 检查时间冲突
    private boolean checkTimeConflict(ClassTable classTable, Member member, Model model) {
        Integer memberAccount = member.getMemberAccount();
        if (!classOrderService.findConflictClasses(memberAccount, classTable.getClassBegin()).isEmpty()) {
            model.addAttribute("errorMessage", "⏰ 该时间段已有其他课程！");
            return true;
        }
        return false;
    }

    // 辅助方法 - 执行选课逻辑
    private void performEnrollment(Integer classId, ClassTable classTable, Member member, HttpSession session) {
        // 创建课程订单
        ClassOrder classOrder = new ClassOrder(
                classTable.getClassId(),
                classTable.getClassName(),
                classTable.getCoach(),
                member.getMemberName(),
                member.getMemberAccount(),
                classTable.getClassBegin()
        );

        // 插入订单
        classOrderService.insertClassOrder(classOrder);

        // 计算课程所需课时
        BigDecimal classTimeInHours = calculateClassHours(classTable);

        // 更新会员剩余课时
        BigDecimal cardNextClass = BigDecimal.valueOf(member.getCardNextClass());
        member.setCardNextClass(cardNextClass.subtract(classTimeInHours).doubleValue());
        session.setAttribute("user", member);

        // 更新数据库中的剩余课时
        memberService.updateMemberCardNextClass(member.getMemberAccount(), member.getCardNextClass());
    }

    // 辅助方法 - 获取并添加已选课程数据到模型
    private void addClassOrdersToModel(Member member, Model model) {
        List<ClassOrder> classOrderList = classOrderService.selectClassOrderByMemberAccount(member.getMemberAccount());
        model.addAttribute("classOrderList", classOrderList);
    }

    // 器械状态列表
    @RequestMapping("/toEquipmentStatus")
    public String equipmentStatus(Model model) {
        List<Equipment> equipmentList = equipmentService.findAll();
        model.addAttribute("equipmentList", equipmentList);
        return "userEquipmentStatus";
    }

    // 按名称查询器械
    @RequestMapping("/searchEquipment")
    public String searchEquipment(
            @RequestParam String equipmentName,
            Model model) {
        // 这里假设你Mapper里已有一个按名称查询的方法
        List<Equipment> equipmentList = equipmentService.selectByEquipmentName(equipmentName);
        model.addAttribute("equipmentList", equipmentList);
        return "userEquipmentStatus";
    }

    // 跳转会员主页
    @RequestMapping("/toUserMain")
    public String toUserMain(Model model, HttpSession session) {
        // 1. 从 session 获取当前登录用户
        Member member = (Member) session.getAttribute("user");
        if (member == null) {
            return "redirect:/login"; // 未登录则跳转
        }


        // 2. 查询该会员的所有课程订单
        Integer memberAccount = member.getMemberAccount();
        List<ClassOrder> classOrderList = classOrderService.selectClassOrderByMemberAccount(memberAccount);


        // 3. 将数据存入 Model
        model.addAttribute("member", member);
        model.addAttribute("classOrderList", classOrderList);// 确保这一行存在
        System.out.println("查询到的课程数量: " + classOrderList.size());
        classOrderList.forEach(System.out::println);

        return "userMain";
    }







}


